import os
from models import *
from utilities import *
from google.appengine.api import users
import UserDict
from Cookie import BaseCookie
from google.appengine.ext import webapp
from django.utils import translation
import hashlib

from gaesessions import get_current_session

def redirect_with_msg(h, msg, dst='/'):
  get_current_session()['msg'] = msg
  h.redirect(dst)

class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}, mime = "text/html"):

    if session.has_key('msg'):
      message = session['msg']
      del session['msg'] # only show the message once
    else:
      message = ''

    values = {
      'message': message,
    }
    
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    if mime == "text/xml":
      self.response.headers['Content-Type'] = "text/xml"
    self.response.out.write(template.render(path, values, debug=_DEBUG))


class addToCart(BaseRequestHandler):
  def post(self):
    productId = self.request.get("productId")

    session = get_current_session()
    if session.has_key('numProd'):
      numProd = session['numProd'] + 1
    else:
      numProd = 1
    session['numProd'] = numProd

    if session.has_key('products'):
      products = session['products']
    else:
      products = []
    products.append(productId)
    session['products'] = products

    self.response.out.write(numProd)


class removeFromCart(BaseRequestHandler):
  def post(self):
    productId = self.request.get("productId")

    session = get_current_session()
    numProd = session['numProd']
    if numProd > 0:
      numProd = numProd - 1

    session['numProd'] = numProd

    products = session['products']
    products.remove(productId)
    session['products'] = products

    self.response.out.write(numProd)
